package org.example.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.example.Entity.Comment;
import org.example.Entity.Community;
import org.example.Entity.User;
import org.example.Mapper.CommentMapper;
import org.example.Mapper.CommunityMapper;
import org.example.Mapper.UserMapper;
import org.example.Service.CommentService;
import org.example.Service.CommunityService;
import org.example.Utils.HttpUtil;
import org.example.Vo.CommentVO;
import org.example.Vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Resource
    private HttpUtil httpUtil;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public R publishComment(Comment comment, String username) {
        Integer userId = httpUtil.getUserId(username);
        comment.setUserId(userId);
        comment.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
        commentMapper.insert(comment);
        LambdaQueryWrapper<Community> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Community::getId,comment.getCommunityId());
        Community community = communityMapper.selectOne(queryWrapper);
        community.setCommentCount(community.getCommentCount()+1);
        communityMapper.updateById(community);
        return R.ok();
    }

    @Override
    public R getCommentById(Integer commentId) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getCommunityId,commentId);
        List<Comment> list = this.list(queryWrapper);
        List<CommentVO> commentVOList = new ArrayList<>();
        for (Comment comment : list) {
            LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
            userQueryWrapper.eq(User::getId,comment.getUserId());
            User user = userMapper.selectOne(userQueryWrapper);
            commentVOList.add(
                    CommentVO.builder()
                            .id(comment.getId())
                            .content(comment.getContent())
                            .createTime(comment.getCreateTime())
                            .username(user.getUsername())
                            .avatarUrl(user.getAvatarUrl())
                            .build());
        }
        return R.ok(commentVOList);
    }
}
